class RealTimeMoisture {
    constructor() {
        this.distributionChart = null;
        this.moisture24HChart = null;
        
        // 等待 DOM 加载完成后再初始化
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.initialize());
        } else {
            this.initialize();
        }
    }

    initialize() {
        // 初始化时立即更新数据
        this.updateOverviewData();
        this.initCharts();
        this.initEventListeners();
        // 初始化时更新一次区域数据
        this.updateAreaData('all');
        this.startRealTimeUpdate();
    }

    initCharts() {
        try {
            // 初始化墒情分布图
            const distCtx = document.getElementById('moistureDistributionChart');
            if (distCtx) {
                this.distributionChart = new Chart(distCtx.getContext('2d'), {
                    type: 'bar',
                    data: {
                        labels: Array.from({length: 12}, (_, i) => `监测点${i + 1}`),
                        datasets: [{
                            label: '土壤墒情 (%)',
                            data: this.generateMockData(12),
                            backgroundColor: 'rgba(24, 144, 255, 0.6)',
                            borderColor: 'rgba(24, 144, 255, 1)',
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true,
                                max: 100
                            }
                        }
                    }
                });
            }

            // 初始化24小时变化图
            const timeCtx = document.getElementById('moisture24HChart');
            if (timeCtx) {
                this.moisture24HChart = new Chart(timeCtx.getContext('2d'), {
                    type: 'line',
                    data: {
                        labels: this.generate24HLabels(),
                        datasets: [{
                            label: '土壤墒情 (%)',
                            data: this.generateMockData(24),
                            borderColor: 'rgba(24, 144, 255, 1)',
                            tension: 0.4,
                            fill: true,
                            backgroundColor: 'rgba(24, 144, 255, 0.1)'
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true,
                                max: 100
                            }
                        }
                    }
                });
            }
        } catch (error) {
            console.error('初始化图表时出错:', error);
        }
    }

    initEventListeners() {
        // 区域选择器事件监听
        document.getElementById('area-selector').addEventListener('change', (e) => {
            this.updateAreaData(e.target.value);
        });
    }

    generate24HLabels() {
        const labels = [];
        const now = new Date();
        for (let i = 23; i >= 0; i--) {
            const time = new Date(now - i * 3600000);
            labels.push(`${time.getHours()}:00`);
        }
        return labels;
    }

    generateMockData(count) {
        return Array.from({length: count}, () => 25 + Math.random() * 10);
    }

    updateAreaData(areaId) {
        // 更新表格数据
        const mockData = this.generateMockTableData(areaId);
        this.updateTable(mockData);
        
        // 更新分布图
        this.updateDistributionChart(areaId);
    }

    generateMockTableData(areaId) {
        const data = [];
        const points = areaId === 'all' ? 12 : 12;
        
        for (let i = 1; i <= points; i++) {
            const moisture = 20 + Math.random() * 30;
            const temperature = 18 + Math.random() * 10;
            
            const areaNumber = areaId === 'all' ? Math.ceil(i / (12/5)) : parseInt(areaId.replace('area', ''));
            
            data.push({
                point: `监测点${i}`,
                area: `区域${areaNumber}`,
                moisture: moisture.toFixed(1),
                temperature: temperature.toFixed(1),
                status: this.getMoistureStatus(moisture),
                time: new Date().toLocaleTimeString()
            });
        }
        
        return data;
    }

    getMoistureStatus(moisture) {
        if (moisture < 20) {
            return { text: '偏低', class: 'danger' };
        } else if (moisture > 40) {
            return { text: '偏高', class: 'warning' };
        }
        return { text: '正常', class: 'normal' };
    }

    updateTable(data) {
        const tbody = document.getElementById('moisture-data-body');
        tbody.innerHTML = data.map(item => `
            <tr>
                <td>${item.point}</td>
                <td>${item.area}</td>
                <td>${item.moisture}</td>
                <td>${item.temperature}</td>
                <td><span class="status-tag ${item.status.class}">${item.status.text}</span></td>
                <td>${item.time}</td>
            </tr>
        `).join('');
    }

    updateDistributionChart(areaId) {
        let labels, data;
        
        if (areaId === 'all') {
            labels = Array.from({length: 5}, (_, i) => `区域${i + 1}`);
            data = Array.from({length: 5}, () => {
                return (20 + Math.random() * 30).toFixed(1);
            });
        } else {
            const areaNum = parseInt(areaId.replace('area', ''));
            labels = Array.from({length: 12}, (_, i) => `监测点${i + 1}`);
            data = Array.from({length: 12}, () => {
                return (20 + Math.random() * 30).toFixed(1);
            });
        }

        this.distributionChart.data.labels = labels;
        this.distributionChart.data.datasets[0].data = data;
        this.distributionChart.update();
    }

    updateOverviewData() {
        document.getElementById('avg-moisture').textContent = 
            (25 + Math.random() * 10).toFixed(1);
        document.getElementById('soil-temperature').textContent = 
            (20 + Math.random() * 5).toFixed(1);
        document.getElementById('soil-compactness').textContent = 
            (80 + Math.random() * 20).toFixed(1);
    }

    startRealTimeUpdate() {
        // 每30秒更新一次数据
        setInterval(() => {
            this.updateOverviewData();
            this.updateAreaData(document.getElementById('area-selector').value);
            this.updateMoisture24HChart();
        }, 30000);
    }

    updateMoisture24HChart() {
        const newData = this.generateMockData(24);
        this.moisture24HChart.data.datasets[0].data = newData;
        this.moisture24HChart.update();
    }

    refreshCharts() {
        // 确保所有数据都被刷新
        this.updateOverviewData();
        this.updateAreaData(document.getElementById('area-selector').value);
        if (this.distributionChart) {
            this.updateDistributionChart(document.getElementById('area-selector').value);
        }
        if (this.moisture24HChart) {
            this.updateMoisture24HChart();
        }
    }
}

// 创建实例并导出
window.realTimeMoisture = new RealTimeMoisture(); 